package com.vegetable.modules.controller.finance;

import com.alibaba.fastjson.JSONObject;
import com.vegetable.common.utils.R;
import com.vegetable.modules.service.baseData.IFundAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 财务分析数据API控制器
 * 提供财务分析数据接口，供前端图表展示使用
 *
 * @author Qoder
 */
@Slf4j
@RestController
@RequestMapping("/api/financial")
@AllArgsConstructor
@Api(value = "财务分析数据API", tags = "财务分析数据API")
public class FinancialAnalysisApiController {

    private final IFundAccountService fundAccountService;

    /**
     * 获取财务分析数据
     */
    @GetMapping("/analysis")
    @ApiOperation(value = "获取财务分析数据", notes = "获取指定时间段的财务分析数据，供前端图表展示使用")
    public R<JSONObject> getFinancialAnalysis(@RequestParam Integer chartRange) {
        try {
            log.info("获取财务分析数据，时间范围: {}个月", chartRange);
            R result = fundAccountService.financialAnalysis(chartRange);
            if (result.getCode() == 0) {
                return R.data((JSONObject) result.getData());
            } else {
                return R.fail(result.getMsg());
            }
        } catch (Exception e) {
            log.error("获取财务分析数据时发生异常", e);
            return R.fail("获取数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取总体财务分析数据
     */
    @GetMapping("/summary")
    @ApiOperation(value = "获取总体财务分析数据", notes = "获取总体财务分析数据")
    public R<JSONObject> getFinancialSummary(@RequestParam Integer chartRange) {
        try {
            log.info("获取总体财务分析数据，时间范围: {}个月", chartRange);
            R result = fundAccountService.financialAnalysis(chartRange);
            if (result.getCode() == 0) {
                JSONObject data = (JSONObject) result.getData();
                return R.data(data.getJSONObject("totalAnalyse"));
            } else {
                return R.fail(result.getMsg());
            }
        } catch (Exception e) {
            log.error("获取总体财务分析数据时发生异常", e);
            return R.fail("获取数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取月度财务分析数据
     */
    @GetMapping("/monthly")
    @ApiOperation(value = "获取月度财务分析数据", notes = "获取月度财务分析数据")
    public R<Object> getMonthlyFinancialData(@RequestParam Integer chartRange) {
        try {
            log.info("获取月度财务分析数据，时间范围: {}个月", chartRange);
            R result = fundAccountService.financialAnalysis(chartRange);
            if (result.getCode() == 0) {
                JSONObject data = (JSONObject) result.getData();
                return R.data(data.get("monthData"));
            } else {
                return R.fail(result.getMsg());
            }
        } catch (Exception e) {
            log.error("获取月度财务分析数据时发生异常", e);
            return R.fail("获取数据失败: " + e.getMessage());
        }
    }
}